package com.da.javatest.thread.juc.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author chenlida
 * @date 2020/7/12 10:50
 * countDownLatch.await(2,TimeUnit.SECONDS);表示最多等2秒，不管计数器是否为0，
 * await方法都会返回，若等待时间内，计数器变为0了，立即返回true，否则超时后返回false。
 */
public class CountDownLatch1 {
    public static class MyThread extends Thread {
        private int sleepTime;
        private CountDownLatch countDownLatch;

        public MyThread(String name, int sleepTime, CountDownLatch countDownLatch) {
            super(name);
            this.sleepTime = sleepTime;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            Thread thread = Thread.currentThread();
            long startTime = System.currentTimeMillis();
            System.out.println(thread.getName() + " 开始处理");
            try {
                TimeUnit.SECONDS.sleep(sleepTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
            long endTime = System.currentTimeMillis();
            System.out.println(thread.getName() + " 处理完毕，耗时：" + (startTime - endTime));
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        long startTime = System.currentTimeMillis();
        new MyThread("sheet1", 2, countDownLatch).start();
        new MyThread("sheet2", 5, countDownLatch).start();
        //countDownLatch.await();
        boolean result = countDownLatch.await(2, TimeUnit.SECONDS);
        long endTime = System.currentTimeMillis();
        //System.out.println("总耗时：" + (startTime - endTime));
        System.out.println("总耗时：" + (startTime - endTime) + ",result:" + result);
    }
}
